package com.fintecher.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.alibaba.fastjson.JSON;
import com.fintecher.pojo.*;
import com.fintecher.service.IPowerService;
import com.fintecher.service.IRoleService;
import com.fintecher.service.IUserRoleService;
import com.fintecher.service.IUserService;
import com.fintecher.utils.Page;
import com.fintecher.utils.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IPowerService powerService;
    @Autowired
    IUserRoleService iUserRoleService;
    Logger logger = Logger.getLogger(this.getClass());

    /*
    *
    * 用户注册
    * */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(HttpServletResponse response, User user, HttpServletRequest request) throws Exception {

        String mes = "用户名不可用!";

        User user1 = userService.find(user.getCompanyUphone(), user.getCompanyName());
        User user3 = userService.find1(user.getCompanyUphone(), user.getCompanyName());
        if (null != user1) {

            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);

        } else if (user3 != null) {

            mes = "用户名不可用!";
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);
        } else {

            userService.adduser(user);
            mes = "用户名可用";
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);
        }
        return null;
    }


    @RequestMapping(value = "checklogin", method = RequestMethod.POST)
    public String checkLogin(User user, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        //获取页面传过来的账号
        String tname = user.getCompanyUphone();
        user.setCompanyUphone(tname);
        String mes = "用户名可用!";
        User userLogin = userService.Longin1(user);
        //判断用户名是否正确，正确则登录，错误则提示重新输入
        if (null != userLogin) {
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);
        } else {
            mes = "用户名不正确！";
            //设置字符集
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);
        }
        return null;
    }

    /*
    * 用户登录
    *
    * */
    @RequestMapping(value = "login")
    public String login(User user, HttpServletRequest request, SessionUtils sessionUtils, HttpSession session, HttpServletResponse response) throws IOException {
        String tname = user.getCompanyUphone();
        String tpwd = user.getPassword();
        user.setCompanyUphone(tname);
        user.setPassword(tpwd);
        String mes = "用户名可用!";
        User user2 = userService.Longin(user);
        session.setAttribute("user", user2);
        //判断用户名及密码是否正确，正,确则登录，错误则提示重新输入
        if (user2 != null) {
            //设置字符集
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);

        } else {
            mes = "用户名不正确！";
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(mes);
        }
        return null;

    }


    /*
* 游客登录
*
* */
    @RequestMapping("visit")
    public String visit(HttpServletRequest request,HttpSession session,Integer id,Role role,User user){
        session.setAttribute("user",user);
          user.getId();
        role.setUserId(id);
        List<Role> roleList = roleService.selAllPower(role);
        logger.info(JSON.toJSONString(roleList));
        request.setAttribute("roles",roleList);
        return "main";
    }

/*
*
* 游客登录成功
* 跳转主页
*
* */
    @RequestMapping("visit1")
    public String visit1(HttpServletRequest request,HttpSession session,Integer id,Role role){
        return "main";
    }

    /*
    * 跳转注册页面
    *
    * */
    @RequestMapping("/tosignIn")
    public String tosignIn() {
        return "/signIn";
    }


    /*
    * 用户信息修改和完善
    *
    * */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)

    public String updateUser(Model model, User user, HttpServletRequest request, HttpSession session) {
        //根据日期生成随机数12位，未来100年不会重复
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
        String ss = dateFormat.format(new Date());
        user.setCompanyNumber(ss);
        User userSession = (User) session.getAttribute("user");
        if(user.getCreatePerson() == null){
            user.setCreatePerson(userSession.getId());
        }
        if (userSession.getSuperiorId() == null) {
            user.setSuperiorId(userSession.getId());
        }
        //完善信息模块进行修改
        if (userService.update(user)) {
            //修改信息成功之后重新查询存入session
            User user2 = userService.Longin(userSession);
            session.setAttribute("user", user2);

            user = userService.findUserByUphone(user.getCompanyUphone());
            /*完善信息完成赋予管理员角色*/
            UserRole userRole = new UserRole();
            userRole.setUserid(userSession.getId());
            userRole.setRoleid(2);
            iUserRoleService.addUserRole(userRole);
            logger.info(JSON.toJSONString(user));
            request.setAttribute("user", user);
            return null;
        }
        return null;
    }


    /**
     * 查询本账号下所有的用户
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selUserGroup")
    public String selUserGroup(Role role,HttpSession session,HttpServletRequest request,String pageNow,Model model) {
        User userGroup = (User) request.getSession().getAttribute("user");
        Role role2 = new Role();
        role2.setUserId(userGroup.getId());
        Page page = null;//new 对象在下面
        int totalCount = userService.getCount(role2.getUserId());//获取当前用户总记录条数
        if(pageNow != null && pageNow!= "") {//防止出现空指针异常
            int pageNow1 = Integer.parseInt(pageNow);
            page = new Page(totalCount, pageNow1);//这样写的好处，判断完成外面可以继续调用
        }else {
            pageNow="1";
            int pageNow1 = Integer.parseInt(pageNow);
            page = new Page(totalCount, pageNow1);
        }
        role2.setPage(page);
        model.addAttribute("page",page);
        List<Role> roleList1 = roleService.sel(role2);
        for(int i=0;i<roleList1.size();i++){
            if(roleList1.size()>1) {
                role2.setUserId(roleList1.get(i).getId());
                List<Role> roleList2 = roleService.sel(role2);
                roleList1.addAll(roleList2);
                if(roleList2.size() ==0){
                    break;
                }
            }
        }

        logger.info(JSON.toJSONString(roleList1));
        request.setAttribute("roles", roleList1);
/*
*
*
* 查询本帐号下所有用户
*
* */
        User user=(User)session.getAttribute("user");
        role.setUserId(user.getId());
        List<Role> roleList = roleService.selAllPower(role);
        request.setAttribute("rle",roleList);

        /**
         * 查看本帐号下所有的用户组
         */
        List<Role> role1 = roleService.roleList(userGroup);
        request.setAttribute("rl", role1);

        return "user_manage";
    }


    /**
     * 添加子用户
     *
     * @param user
     * @return
     */

    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public void addUser(User user, HttpServletResponse response, HttpSession session) throws Exception {
        //从session中获取经办人信息，为登陆者id
        User userSession = (User) session.getAttribute("user");
        Integer roper = userSession.getId();
        user.setCreatePerson(roper);
        user.setSuperiorId(roper);
        //添加子用户
        userService.addUserMin(user);

        UserRole userRole = new UserRole();
        userRole.setUserid(user.getId());
        userRole.setRoleid(user.getUserGroup());
        userRoleService.addUserRole(userRole);
        String result = "success";
        response.getWriter().write(result);
    }





    @RequestMapping("toUser")
    public String toUser(Model model, HttpServletRequest request, HttpSession session, SessionUtils sessionUtils) {
        User user = (User) request.getSession().getAttribute("user");
        model.addAttribute("user", user.getCompanyUname());
        return "main";
    }


    /*
    * 跳转到用户信息界面
    *
    * */
    @RequestMapping("/toUsers")
    public String toUsers(HttpServletRequest request, HttpSession session, SessionUtils sessionUtils) {
        User users = (User) request.getSession().getAttribute("user");
        List<User> user = userService.finds(users.getCompanyUphone());
        logger.info(JSON.toJSONString(user));
        request.setAttribute("userList", user);
        return "users";
    }




    /**
     * 删除用户，进行逻辑删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "delUser")
    public void delUser(Integer id, HttpServletResponse response) throws Exception {
        userService.delUser(id);
        String result = "success";
        response.getWriter().write(result);
    }


    /**
     * 修改用户禁用启用按钮
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "updateUserIsdisables")
    public void updateUserIsdisables(Integer id, Integer isdisables, HttpServletResponse response) throws Exception {
        User user = new User();
        user.setId(id);
        if (isdisables == 0) {
            user.setIsdisables(1);
            userService.updateUserIsdisables(user);
            String result = "success";
            response.getWriter().write(result);
        } else if (isdisables == 1) {
            user.setIsdisables(0);
            userService.updateUserIsdisables(user);
            String result = "success";
            response.getWriter().write(result);
        }
    }

    /**
     * 退出用户清除session
     *
     * @return
     */
    @RequestMapping(value = "loginout")
    public void loginout(HttpSession session, HttpServletResponse response) throws Exception {
        session.invalidate();
        String result = "success";
        response.getWriter().write(result);
    }


}


